package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 根据id查询商铺
     * @param id
     * @return
     */
    public Result queryById(Long id) {
        //缓存穿透

        //互斥锁解决缓存击穿
        Shop shop = queryWithMutex(id);
        if (shop == null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }

    //利用互斥锁解决缓存击穿
    public Shop queryWithMutex(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //从Redis查询店铺缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(key);

        //命中Redis，存在直接返回
        if (StrUtil.isNotBlank(cacheShop)){
            return JSONUtil.toBean(cacheShop, Shop.class);
        }
        if (cacheShop != null){
            return null;
        }

        //未命中Redis，先获取锁，再查询数据库
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id ;
        Shop shop = null;
        try {
            boolean lock = tryLock(lockKey);
            //失败休眠重试
            if (!lock){
                Thread.sleep(50);
                queryWithMutex(id);
            }
            //重建
            shop = getById(id);
            //店铺不存在，写入Redis空值，防止缓存穿透
            if (shop == null){
                stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            //存在，写入Redis，并添加过期时间
            stringRedisTemplate.opsForValue().set(key,shop.toString(),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unlock(lockKey);
        }

        return shop;
    }

    //解决缓存穿透
    public Shop queryWithPassThrough(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //从Redis查询店铺缓存
        String cacheShop = stringRedisTemplate.opsForValue().get(key);

        //命中Redis，存在直接返回
        if (StrUtil.isNotBlank(cacheShop)){
            return JSONUtil.toBean(cacheShop, Shop.class);
        }
        if (cacheShop != null){
            return null;
        }

        //未命中Redis，查询数据库
        Shop shop = getById(id);

        //店铺不存在，写入Redis空值，防止缓存穿透
        if (shop == null){
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //存在，写入Redis，并添加过期时间
        stringRedisTemplate.opsForValue().set(key,shop.toString(),RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }


    //尝试获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 更新店铺信息
     * @param shop
     * @return
     */
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺id不能为空!");
        }
       //先更新数据库，再删除缓存
        updateById(shop);
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
